package ch.ti.bfh.app.loodel.internal.security;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class CustomPermissionEvaluator implements PermissionEvaluator {

    private Map<String, Permission> permissionMap = new HashMap<String, Permission>();

    public CustomPermissionEvaluator(Map<String, Permission> permissionMap) {
        this.permissionMap = permissionMap;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObjectId, Object permission) {
        verifyPermissionIsDefined((String) permission);
        return permissionMap.get(permission).isAllowed(authentication, (Serializable) targetDomainObjectId);
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        verifyPermissionIsDefined((String) permission);
        return permissionMap.get(permission).isAllowed(authentication, targetId);
    }

    private void verifyPermissionIsDefined(String permissionKey) {
        if (!permissionMap.containsKey(permissionKey)) {
            throw new PermissionNotDefinedException("No permission with key '" + permissionKey + "' is defined in" + this.getClass().toString());
        }
    }
}
